package org.hepeng.fabric.gateway.contract.spring;

import org.hepeng.fabric.contract.api.annotation.ContractAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Objects;

/**
 * @author he peng
 * @date 2022/3/28
 */
public class ContractScannerRegistrar implements ImportBeanDefinitionRegistrar {

    private static final Logger LOG = LoggerFactory.getLogger(ContractScannerRegistrar.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        AnnotationAttributes contractScanAttrs = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(ContractScan.class.getName()));

        if (Objects.isNull(contractScanAttrs)) {
            LOG.warn("No \"@ContractScan\" annotations was not found, package. Please check your code.");
            return;
        }

        String[] packages = contractScanAttrs.getStringArray("basePackages");

        ClassPathContractScanner scanner = new ClassPathContractScanner(registry);
        scanner.setAnnotationClass(ContractAPI.class);
        scanner.registerFilters();
        scanner.doScan(packages);
    }

}
